#include "util.h"
#include <QMessageBox>
#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QWidget>
#include <QByteArray>
#include <functional>
#include <QJsonArray>
extern void handler_response(QWidget *parent, QNetworkReply *reply ,std::function<void(const QJsonObject &)> success_callback){
    if(reply->error()!=QNetworkReply::NoError)
    {
        QMessageBox::warning(parent,"提示",reply->errorString());
        return;
    }
    QByteArray result =  reply->readAll();
    QJsonDocument j_result = QJsonDocument::fromJson(result);
    QJsonObject jo = j_result.object();
    int code_value =   jo["rep_code"].toInt();
    QString message_value = jo["rep_message"].toString();
    if(code_value!=2000)
    {
        QMessageBox::warning(parent,"提示",message_value);
        return;
    }
    else
    {
        success_callback( jo["data"].toObject());
    }
}

extern void request_server(QWidget *parent,QNetworkAccessManager *network,const QString &url,const QString &params,std::function<void(const QJsonObject &)> success_back){
    QNetworkRequest req;
    req.setUrl(url);
    QByteArray par_byte = params.toUtf8();
    req.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
    QNetworkReply *result =  network->post(req,par_byte);
    parent->connect(result,&QNetworkReply::finished,[=](){
        handler_response(parent,result,success_back);
    });

}

extern void handle_server_result(const QByteArray &message,std::function<void(const int &code,const QJsonDocument &rep_data,const QString &tag)> success_callback,std::function<void (const int &code,const int &rep_code,const QString &rep_message,const QString &tag)> error_callback)
{
    QJsonDocument j_result = QJsonDocument::fromJson(message);
    QJsonObject jo = j_result.object();
    int rep_code =   jo["rep_code"].toInt();
    QString rep_message = jo["rep_message"].toString();
    int code = jo["code"].toInt();
    QString tag = "";
    QJsonValue jv = jo["tag"];
    if(jv.isUndefined())
    {
        tag = "";
    }
    else
    {
        tag = jv.toString();
    }

    if(rep_code==2000)
    {
        QJsonValue v = jo["data"];
        if(v.isArray())
        {
            success_callback(code,QJsonDocument(v.toArray()),tag);
        }
        else if(v.isObject())
        {
            success_callback(code,QJsonDocument(v.toObject()),tag);
        }
    }
    else
    {
        error_callback(code,rep_code,rep_message,tag);
    }
}

extern void send_socket_message(QWebSocket *websocket,const int &code ,const QJsonObject &data,const QString &tag)
{

    if(websocket)
    {
        QJsonObject j;
        j.insert("code",code);
        j.insert("data",data);
        j.insert("tag",tag);
        QJsonDocument document(j);
        websocket->sendBinaryMessage(document.toJson());
    }
}

QString format_unix_time(int unix_time)
{
    qint64 t = (qint64)unix_time*1000;
    return  QDateTime::fromMSecsSinceEpoch(t).toString("HH:mm:ss").append(' ');
}
